package com.example.sociamedia.post.controller;

import com.example.sociamedia.post.dto.PostRequest;
import com.example.sociamedia.post.dto.PostResponse;
import com.example.sociamedia.post.entity.Post;
import com.example.sociamedia.post.mapper.PostMapper;
import com.example.sociamedia.user.entity.User;
import com.example.sociamedia.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;

@Service
public class PostService implements PostApi {

    private final PostMapper postMapper;
    private final UserMapper userMapper;

    @Autowired
    public PostService(PostMapper postMapper, UserMapper userMapper) {
        this.postMapper = postMapper;
        this.userMapper = userMapper;
    }

    @Override
    public PostResponse createPost(String token, PostRequest postRequest) {
        // 通过token查找用户
        User user = userMapper.selectUserByToken(token);
        if (user == null) {
            throw new RuntimeException("无效的用户token");
        }
        Post post = new Post();
        post.setUserId(user.getUserid().intValue());
        post.setContent(postRequest.getContent());
        post.setMediaUrl(postRequest.getMediaUrl());

        // 自动识别mediaType
        String mediaType = "none";
        String url = postRequest.getMediaUrl();
        if (url != null && !url.isEmpty()) {
            String lowerUrl = url.toLowerCase();
            if (lowerUrl.endsWith(".jpg") || lowerUrl.endsWith(".jpeg") || lowerUrl.endsWith(".png") || lowerUrl.endsWith(".gif") || lowerUrl.endsWith(".bmp")) {
                mediaType = "image";
            } else if (lowerUrl.endsWith(".mp4") || lowerUrl.endsWith(".avi") || lowerUrl.endsWith(".mov") || lowerUrl.endsWith(".wmv") || lowerUrl.endsWith(".flv")) {
                mediaType = "video";
            }
        }
        post.setMediaType(mediaType);
        post.setIsPublic(postRequest.getIsPublic() != null ? postRequest.getIsPublic() : true);
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        postMapper.insertPost(post);
        // 构造返回
        PostResponse response = new PostResponse();
        response.setPostId(post.getPostId());
        response.setUserId(user.getUserid());
        response.setContent(post.getContent());
        response.setMediaUrl(post.getMediaUrl());
        response.setMediaType(post.getMediaType());
        response.setIsPublic(post.getIsPublic());
        response.setCreatedAt(post.getCreatedAt());
        response.setUpdatedAt(post.getUpdatedAt());
        return response;
    }


} 